name: Deploy to dev

on:
  pull_request:
    types: [opened, reopened, synchronize, labeled]


jobs:
  get-deploy-labels:
    runs-on: [self-hosted, dev]
    outputs:
      deploy-envs: ${{ steps.make-label-list.outputs.deploy-envs }}
    steps:
      - uses: actions/checkout@v2
      - uses: FranzDiebold/github-env-vars-action@v2
      # Takes PR labels and turns them into env vars: https://github.com/marketplace/actions/pr-labels
      - name: Get PR labels
        id: pr-labels
        uses: joerick/pr-labels-action@v1.0.9
      # Turn env vars from above into a json list of deployment envs
      - id: make-label-list
        run: |
          DEPLOY_LABELS=${!GITHUB_PR_LABEL_DEPLOY_TO_*}           # echo all of the PR label envs on one line
          DEPLOY_ENVS=[\"${DEPLOY_LABELS// /\",\"}\"]             # Turn into a json list like ["ENV_1","ENV_2"]
          DEPLOY_ENVS=${DEPLOY_ENVS//GITHUB_PR_LABEL_DEPLOY_TO_/} # Delete GITHUB_PR_LABEL_DEPLOY_TO_ so we're just left with the deploy env name
          DEPLOY_ENVS=${DEPLOY_ENVS//_/-}                         # Replace underscores with dashes
          DEPLOY_ENVS=${DEPLOY_ENVS//\"\"/}                       # Remove empty strings
          echo "deploy-envs=${DEPLOY_ENVS,,}" >> "$GITHUB_OUTPUT" # Lowercase the whole list and output it
          echo "deploy-envs=${DEPLOY_ENVS,,}"

  build:
    # Build our docker images based on our bake file
    runs-on: [self-hosted, dev]
    needs: [get-deploy-labels]
    if: needs.get-deploy-labels.outputs.deploy-envs != '[]'
    steps:
      - uses: actions/checkout@v2
      # Build the bakefile and push
      - uses: ./.github/actions/docker-bake

  trigger_deploy:
    # Trigger private repo to deploy to dev envs
    runs-on: [self-hosted, dev]
    needs: [build, get-deploy-labels]
    strategy:
      matrix:
        deploy-env: ${{fromJson(needs.get-deploy-labels.outputs.deploy-envs)}}
    environment:
      name: dev
    if: needs.get-deploy-labels.outputs.deploy-envs != '[]'
    steps:
      - uses: FranzDiebold/github-env-vars-action@v2
      - uses: convictional/trigger-workflow-and-wait@v1.6.5
        with:
          owner: mindsdb
          repo: INTERNAL-mindsdb-build-deploy-to-kubernetes
          github_token: ${{ secrets.REPO_DISPATCH_PAT_TOKEN }}
          workflow_file_name: deploy-dev.yml
          ref: master
          client_payload: '{"image-tag-prefix": "${{ env.CI_SHA }}", "deploy-env": "${{matrix.deploy-env}}"}'
